<template>
  <view>
    <uni-section class="title" type="line" :title="classroom_name+'室'" titleFontSize="25px" subTitleFontSize="15px"
      :sub-title="chooseDay+' '+opentime" padding="5px 5px">





      <view class="uni-padding-wrap uni-common-mt">
        <uni-segmented-control :current="current" :values="items" style-type="button" active-color="#2196f3"
          @clickItem="onClickItem" />
      </view>
      <view class="content">
        <!-- 座位热力图 -->
        <view v-if="current === 0">



          <view class="box_container">
            <view class="box" @click="openSeatDialog(item.seat_id)" v-for="item in seatHotList" :key="item"
              :style="'background: rgba(76, 175, 80, '+item.rate+')' ">{{item.num}}
            </view>

          </view>


        </view>


        <!-- 查看时间段 -->
        <view v-if="current === 1">


          <view class="date_time">

            <view style="width: 85px;" @click="openTimePicker" :class="{'date_btn':true,'active_btn':true }">
              选择时间段
            </view>
            <text style="line-height: 30px;">
              {{timePickerStart?timePickerStart+":00:00 - ":""}}{{timePickerEnd?timePickerEnd+":59:59":""}}
            </text>
          </view>





          <view class="box_container">
            <view class="box" @click="openTimeAlert(item)" v-for="item in timePickerlist" :key="item"
              :class="{'grayBtn':!item.available,'greenBtn':item.available}">{{item.num}}
            </view>

          </view>
        </view>

      </view>



    </uni-section>








    <!-- 选择时间弹窗 -->
    <uni-popup ref="popup" background-color="#fff" @change="openSeat">
      <view class="pop_container">
        <view class="hour-pop">
          <view class="hourBlock" v-for="item in rangeTime" :key="item" @click="chooseHour(item)">
            <view
              :class="{'hourLine':true,'active_btn':(item==startTime&&!endTime)||(item>=startTime && item <= endTime),'gray_btn':gray(item)}">
            </view>
            {{item}}:00
          </view>


        </view>
        <view>
          您选择的时间段为：
          <view style="height: 20px;">
            {{chooseDay}} {{startTime?startTime+":00:00-":""}}{{endTime?endTime+":59:59":""}}
          </view>

        </view>

        <view @click="confirmHour" style="width: 90vw;margin-top: 10px;"
          :class="{'date_btn':true,'active_btn':startTime&&endTime }">
          确定
        </view>
      </view>
    </uni-popup>


    <uni-popup ref="timePicker" background-color="fff" @change="changetimePickerPop">
      <view class="timePicker_container">
        <picker-view indicator-style="100rpx" @change="timePickerChange" class="picker-view">
          <picker-view-column>
            <view class="item" v-for="(item, index) in hours0" :key="item">{{ item }}:00:00</view>
          </picker-view-column>
          <text style="line-height: 208px;"> 到</text>

          <picker-view-column>
            <view class="item" v-for="(item, index) in hours1" :key="item">{{ item }}:59:59</view>
          </picker-view-column>

        </picker-view>
        <view @click="confirmTimePicker" style="width: 90vw;margin-top: 10px;"
          :class="{'date_btn':true,'active_btn':timePickerResult[0]<=timePickerResult[1]}">
          确定
        </view>
      </view>
    </uni-popup>

    <!-- 根据时间段选择确认弹窗 -->
    <uni-popup ref="timePickerComfirmDialog" type="dialog">
      <uni-popup-dialog :type="info" cancelText="关闭" confirmText="确定" title="预约座位" :content="alertContent"
        @confirm="dialogConfirm"></uni-popup-dialog>
    </uni-popup>


  </view>


</template>


<script>
  import {
    getSeatsSummary,
    getSeatsAvailable,
    getOpeningStatus,
    getShowaVailable,
    postAddAppointment
  } from "@/api/buildDetail.js"
  export default {

    data() {
      return {
        opentime: "",
        seatHotList: [],
        classroom_name: "",
        hotSeatId: "",

        dateList: [{
          name: "今天",
          value: "2023-6-15"
        }, {
          name: "明天",
          value: "2023-6-16"
        }, {
          name: "后天",
          value: "2023-6-17"
        }],
        items: ['座位热力图', '查看时间段'],
        chooseDay: "2023-6-15",
        current: 0,
        colorIndex: 0,
        hourList: [

        ],
        rangeTime: [],
        startTime: 0,
        endTime: 0,
        classroom_id: "",
        chooseSeat: "",
        occupiedTime: [],
        emptyTime: [],
        checkEmptyIndex: 0,

        //查看时间段
        timePickerResult: [0, 0],
        alertContent: "",
        timeSeatId: "",
        hours0: [],
        hours1: [],
        timePickerStart: 7,
        timePickerEnd: 7,
        timePickerlist: [{
          num: '001',
          isEmpty: true
        }, {
          num: "002",
          isEmpty: false
        }, {
          num: "003",
          isEmpty: true
        }, {
          num: "004",
          isEmpty: false
        }],
      }
    },
    onLoad(option) {
      this.classroom_id = option.classroom_id;
      this.classroom_name = option.classroom_name;
      this.chooseDay = option.chooseDay;
      this.getSeatsSummary();
      this.getOpeningStatus();
      if (option.seat_id) {
        this.openSeatDialog(option.seat_id)
      }
    },

    methods: {
      getOpeningStatus() {
        getOpeningStatus({
          time: this.chooseDay,
          classroom_id: this.classroom_id
        }).then(res => {
          this.opentime = res.data.data.start_time.slice(11, 16) + '-' + res.data.data.end_time.slice(11, 16) +
            '开放';
          let start_time = Number(res.data.data.start_time.slice(11, 13));
          let end_time = Number(res.data.data.end_time.slice(11, 13));
          for (var i = start_time; i < end_time; i++) {
            this.rangeTime.push(i);
            this.hours0.push(i);
            this.hours1.push(i);
          }


        })
      },
      getSeatsSummary() {
        getSeatsSummary({
          classroom_id: this.classroom_id,
          time: this.chooseDay
        }).then(res => {
          this.seatHotList = res.data.data
        })
      },

      //接收子组件传过来的新值
      complete(val) {
        console.log(val)
      },
      gray(value) {
        for (let arr in this.occupiedTime) {
          if (value >= this.occupiedTime[arr][0] && value <= this.occupiedTime[arr][1]) {

            return true;
          }

        }
        return false;
      },
      openSeatDialog(seat_id) {
        this.$refs.popup.open('bottom')
        this.hotSeatId = seat_id;
        getShowaVailable({
          seat_id,
          classroom_id: this.classroom_id,
          time: this.chooseDay
        }).then(res => {
          this.emptyTime = [];
          this.occupiedTime = [];
          //处理被占用的时间段
          res.data.data.unavailableTimeRangeList.forEach(el => {
            if (el) {
              let start = Number(el.start_time.slice(11, 13));
              let end = Number(el.end_time.slice(11, 13));

              if (el.end_time.slice(14, 16) == '00')
                end = end - 1;
              this.occupiedTime.push([start, end])
            }
          })
          //处理空闲时间段
          res.data.data.availableTimeRangeList.forEach(el => {
            if (el) {
              let start = Number(el.start_time.slice(11, 13));
              let end = Number(el.end_time.slice(11, 13));

              if (el.end_time.slice(14, 16) == '00')
                end = end - 1;
              this.emptyTime.push([start, end])
            }
          })
        })
      },
      onClickItem(e) {
        if (this.current !== e.currentIndex) {
          this.current = e.currentIndex
          if (this.current == 1) {
            console.log(this.numberToHour(this.timePickerStart))
            console.log(this.numberToHour(this.timePickerEnd, 1))
            this.getSeatsAvailable()
          } else {
            this.getSeatsSummary()
          }
        }
      },
      getSeatsAvailable() {
        getSeatsAvailable({
          classroom_id: this.classroom_id,
          start_time: this.numberToHour(this.timePickerStart),
          end_time: this.numberToHour(this.timePickerEnd, 1)
        }).then(res => {

          this.timePickerlist = res.data.data;
        })
      },
      styleChange(e) {
        if (this.styleType !== e.detail.value) {
          this.styleType = e.detail.value
        }
      },
      colorChange(e) {
        if (this.styleType !== e.detail.value) {
          console.log(e.detail.value);
          this.activeColor = e.detail.value
        }
      },

      checkStart(i) {
        for (time in this.occupiedTime)
          isRangeIn(i, time[0], time[1])

      },

      //参数str判断的字符串 m最小值 n最大值
      isRangeIn(str, minnum, maxnum) {
        debugger;
        var num = parseFloat(str);

        if (num <= maxnum && num >= minnum) {

          return true;
        }

        return false;

      },
      chooseHour(item) {
        if (!this.startTime) {

          this.startTime = this.checkStartTime(item);
        } else if (!this.endTime) {
          this.endTime = this.checkEndTime(item);
        } else {
          this.startTime = this.checkStartTime(item);;
          this.endTime = 0;
        }


      },
      checkStartTime(value) {
        for (let i in this.emptyTime) {
          if (value >= this.emptyTime[i][0] && value <= this.emptyTime[i][1]) {
            this.checkEmptyIndex = i;
            return value;
          }

        }
        return 0;
      },
      checkEndTime(value) {
        // debugger;
        if (value < this.startTime) {
          this.startTime = this.checkStartTime(value);
          return 0;
        }


        if (value > this.emptyTime[this.checkEmptyIndex][1]) return this.emptyTime[this.checkEmptyIndex][1];
        else return value;


        return value

      },

      confirmHour() {
        if (this.startTime && this.endTime) {
          let user_id = wx.getStorageSync('iseats_userInfo').user_id;
          let seat_id = this.hotSeatId;
          let start_time = this.numberToHour(this.startTime)
          let end_time = this.numberToHour(this.endTime, 1)
          console.log(start_time, end_time)

          if (new Date(start_time) < new Date()) {
            uni.showToast({
              title: `请选择未来时间段`,
              icon: 'none'
            });
            return
          }

          postAddAppointment({
            user_id,
            seat_id,
            start_time,
            end_time
          }).then(res => {
            if (res.data.status == 200) {
              uni.showToast({
                title: '预约成功',
                icon: "none"
              })
            }
            this.getSeatsSummary();
          })


          this.startTime = 0;
          this.endTime = 0;
          

          this.$refs.popup.close();
        }

      },
      numberToHour(number, isEnd = 0) {
        if (isEnd) number++;
        if (number < 10)
          number = '0' + number.toString()
        else
          number = number.toString()

        return this.chooseDay + ' ' + number + ':00:00'
      },

      openSeat() {


      },

      //查看时间段
      openTimePicker() {
        this.$refs.timePicker.open('bottom')
      },
      changetimePickerPop() {},


      timePickerChange(ev) {
        let data = ev.detail.value
        console.log(data)
        this.timePickerResult = data
      },
      confirmTimePicker() {
        if (this.timePickerResult[0] > this.timePickerResult[1])
          return;
        this.timePickerStart = this.hours0[this.timePickerResult[0]];
        this.timePickerEnd = this.hours1[this.timePickerResult[1]]
        this.$refs.timePicker.close();
        this.timePickerResult = [0, 0];
        this.getSeatsAvailable();

      },

      openTimeAlert(item) {
        if (!item.available) return;
        let start_time = this.numberToHour(this.timePickerStart);
        if (new Date(start_time) < new Date()) {
          uni.showToast({
            title: `请选择未来时间段`,
            icon: 'none'
          });
          return
        }
        this.timeSeatId = item.seat_id;


        this.alertContent = `确定预约 ${start_time} 到 ${this.numberToHour(this.timePickerEnd, 1)} 的 ${item.num} 座吗?`

        this.$refs.timePickerComfirmDialog.open()
      },

      dialogConfirm() {

        let user_id = wx.getStorageSync('iseats_userInfo').user_id;
        let seat_id = this.timeSeatId;
        let start_time = this.numberToHour(this.timePickerStart)
        let end_time = this.numberToHour(this.timePickerEnd, 1)
        console.log(start_time, end_time)

        if (new Date(start_time) < new Date()) {
          uni.showToast({
            title: `请选择未来时间段`,
            icon: 'none'
          });
          return
        }

        postAddAppointment({
          user_id,
          seat_id,
          start_time,
          end_time
        }).then(res => {
          if (res.data.status == 200) {
            uni.showToast({
              title: '预约成功',
              icon: "none"
            })
            this.getSeatsAvailable();
          }
        })
        this.$refs.timePickerComfirmDialog.close();

      }
    }
  }
</script>

<style lang="scss">
  .date_time {
    display: flex;
    flex-wrap: wrap;
    overflow: hidden;
  }

  .date_btn {
    width: 100rpx;
    height: 60rpx;
    margin-right: 30rpx;
    margin-bottom: 30rpx;
    border-radius: 10rpx;
    display: flex;
    background-color: #9bd9ff;
    color: #fff;
    align-items: center;
    justify-content: center;
  }

  .active_btn {
    background-color: #2196f3;
  }

  .content {
    padding-top: 15px;
  }

  .box_container {
    display: flex;
    flex-wrap: wrap;
    overflow: hidden;
    padding: 10px;
  }

  .box {
    font-size: 12px;
    width: 33px;
    height: 33px;
    margin-right: 10px;
    margin-bottom: 10px;
    border-radius: calc(calc(800rpx / 8.75) / 6);
    display: flex;
    border: 1px solid rgba(76, 175, 80, 0.8);
    align-items: center;
    justify-content: center;

    &::last-child {
      margin-right: 0;
    }
  }

  .grayBtn {
    background-color: #cecece;
  }

  .greenBtn {
    background: rgba(76, 175, 80, 0.4)
  }

  .pop_container {
    padding: 10px;
  }

  .hour-pop {
    display: flex;
    flex-wrap: wrap;
    overflow: hidden;


    .hourBlock {
      margin-right: 5px;
      margin-bottom: 10px;
      font-size: 12px;
      color: #666;

      .hourLine {
        width: 120rpx;
        height: 20rpx;
        background-color: #9bd9ff;
      }

      .active_btn {
        background-color: #2196f3;
      }

      .gray_btn {
        background-color: #cecece;
      }
    }
  }


  //查看时间段
  .picker-view {
    height: 400rpx;
    background: #fff;
  }

  .item {
    line-height: 34px;
    text-align: center;
  }

  .timePicker_container {
    background-color: #fff;
    padding: 20px;
  }
</style>